<template>
  <div
    v-for="(forms, index) in formList"
    :key="index + 'key'"
    class="card-list"
  >
    <el-card :key="index" class="card">
      <template #header>
        <div class="card-header">
          <div class="titles">第{{ numberToChinese(index + 1) }}完成人</div>
          <el-button
            v-if="index != 0"
            :disabled="isDisabled"
            @click="remove(index)"
          >
            移除
          </el-button>
        </div>
      </template>
      <el-form
        ref="formRef8"
        :model="forms"
        :rules="rules"
        class="form-inline mt20"
        label-width="auto"
        label-position="top"
        :disabled="isDisabled"
      >
        <el-form-item
          v-for="(item, j) in form8"
          :key="j"
          :label="item.label"
          :prop="item.prop"
        >
          <!-- input -->
          <el-input
            v-if="item.type === 'input'"
            v-model="forms[item.prop]"
            placeholder="请输入"
            :disabled="item.isDisabled"
            clearable
          />
          <!-- select -->
          <el-select
            v-if="item.type === 'select'"
            v-model="forms[item.prop]"
            :filterable="item.isSearch"
            placeholder="请选择"
          >
            <el-option
              v-for="x in item.options"
              :key="x.value"
              :label="x.label"
              :value="x.value"
            />
          </el-select>

          <!-- textarea -->
          <el-input
            v-if="item.type === 'textarea'"
            v-model="forms[item.prop]"
            placeholder="请输入"
            :rows="4"
            type="textarea"
            clearable
          />

          <!-- date -->
          <el-date-picker
            v-if="item.type === 'date'"
            v-model="forms[item.prop]"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="曾获奖励及荣誉称号:"
          prop="n"
          style="grid-column: span 3"
        >
          <el-input
            v-model="forms.n"
            placeholder="请输入"
            :rows="6"
            type="textarea"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="参加本项目时间和主要贡献:"
          style="grid-column: span 3"
        >
          <vxe-grid
            ref="xGrid8"
            v-bind="form8GridOptions"
            :height="height"
            style="width: 100%; margin-top: 20px"
          >
            <template #operate="{ row }">
              <template v-if="hasActiveEditRow(row, index)">
                <vxe-button content="取消" @click="clearRowEvent" />
                <vxe-button
                  status="primary"
                  content="保存"
                  @click="saveRowEvent(row, index)"
                />
              </template>
              <template v-else>
                <vxe-button
                  content="编辑"
                  :disabled="isDisabled"
                  @click="editRowEvent(row, index)"
                />
              </template>
              <vxe-button
                status="danger"
                content="删除"
                style="margin-top: 20px"
                :disabled="isDisabled"
                @click="removeRowEvent(row)"
              />
            </template>
            <template #date_edit="{ row }">
              <el-date-picker
                v-model="row.date"
                type="daterange"
                range-separator="→"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                clearable
                @change="handTimeChange($event, row)"
              />
            </template>
            <template #content_edit="{ row }">
              <vxe-input v-model.number="row.content" />
            </template>
            <template #dayNum_edit="{ row }">
              <vxe-input v-model.number="row.dayNum" />
            </template>
          </vxe-grid>
          <el-button
            type="primary"
            text
            :icon="Plus"
            :disabled="isDisabled"
            @click="addInventor(index)"
          >
            增加行
          </el-button>
        </el-form-item>
        <el-form-item
          label="推荐单位意见:"
          prop="x"
          style="grid-column: span 3"
        >
          <el-input
            v-model="forms.x"
            placeholder="请输入"
            :rows="6"
            type="textarea"
            clearable
          />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  <el-button
    type="primary"
    text
    :icon="Plus"
    :disabled="isDisabled"
    @click="addCard"
  >
    增加完成人
  </el-button>
</template>

<script setup lang="ts">
  import {
    ref,
    reactive,
    defineExpose,
    defineProps,
    withDefaults,
    onMounted,
    computed,
    watch,
  } from 'vue'
  import { form8, form8GridOptions } from '../table/column'
  import { Delete, Plus } from '@element-plus/icons-vue'
  import {
    VXETable,
    VxeGridInstance,
    VxeGridProps,
    VxeGridListeners,
  } from 'vxe-table'
  import { useAchievementAwardStore } from '@/store/modules/achievementAward'
  import { storeToRefs } from 'pinia'
  import { useDictStore } from '@/store/modules/dict'
  import { isPhone } from '@/utils/validate'

  const validatePhone = (rule, value, callback) => {
    if (value && !isPhone(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }
  const dictStore = useDictStore()
  const props = withDefaults(
    defineProps<{
      isDisabled?: boolean
      isUpdate?: boolean
    }>(),
    {
      isDisabled: false,
      isUpdate: false,
    }
  )
  const formRef8 = ref()
  const totalDay = ref(0)
  const rules = reactive({
    g: [{ validator: validatePhone, trigger: 'blur' }],
  })
  const xGrid8 = ref()
  const store = useAchievementAwardStore()
  const { UserList, DeptList, eduList, allForm } = storeToRefs(store)
  const getOptions = computed(() => ({
    a: UserList.value || [],
    b: dictStore.getDictType('system_user_sex') || [],
    d: DeptList.value || [],
    m: eduList.value || [],
  }))
  watch(
    [UserList, DeptList],
    () => {
      form8.forEach((item) => {
        item.options = getOptions.value[item.prop] || []
      })
    },
    { deep: true, flush: 'post' }
  )

  watch(
    () => props.isUpdate,
    (val) => {
      formList.value = JSON.parse(allForm.value.majorCompletePersons ?? '[]')
      // console.log(formList.value, '===')
      formList.value.forEach((item, index) => {
        const $grid = xGrid8.value[index]
        if ($grid) {
          const data = JSON.parse(item.data || '[]')?.tableData
          $grid.reloadData(data)
        }
      })
    }
  )

  const formItem = ref({
    a: '',
    b: '',
    c: '',
    d: '',
    e: '',
    f: '',
    g: '',
    h: '',
    i: '',
    j: '',
    k: '',
    l: '',
    m: '',
    n: '',
    x: '',
    data: '',
  })
  const formList = ref([])
  formList.value.push(formItem.value)

  const addCard = () => {
    formItem.value = {
      a: '',
      b: '',
      c: '',
      d: '',
      e: '',
      f: '',
      g: '',
      h: '',
      i: '',
      j: '',
      k: '',
      l: '',
      m: '',
      n: '',
      x: '',
      data: '',
    }
    formList.value.push(formItem.value)
  }

  const remove = (index) => {
    formList.value.splice(index, 1)
  }

  const validFormItem = async () => {
    const ok = []
    try {
      await Promise.all(
        formRef8.value.map(async (item) => {
          try {
            const valid = await item.validate()
            if (valid) {
              ok.push('ok')
            }
          } catch (error) {
            console.log(error)
          }
        })
      )
    } catch (e) {
      return false
    }

    return ok
  }

  const { addForm } = store
  const submit = async () => {
    const ok = await validFormItem()
    if (ok.length === formRef8.value.length) {
      console.log(formList.value, '====')
      const obj = { majorCompletePersons: JSON.stringify(formList.value) }
      addForm(obj)
    }
  }

  const hasActiveEditRow = (row, index) => {
    const $grid = xGrid8.value[index]
    if ($grid) {
      return $grid.isEditByRow(row)
    }
    return false
  }
  const editRowEvent = (row, index) => {
    const $grid = xGrid8.value[index]
    if ($grid) {
      $grid.setEditRow(row)
    }
  }

  const saveRowEvent = async (row, index) => {
    const $grid = xGrid8.value[index]
    if ($grid) {
      await $grid.clearEdit()
      formList.value[index].data = JSON.stringify($grid.getTableData())
      // form8GridOptions.loading = true
      // // 模拟异步保存
      // setTimeout(() => {
      //   form8GridOptions.loading = false
      // }, 300)
    }
  }

  const clearRowEvent = (index) => {
    const $grid = xGrid8.value[index]
    if ($grid) {
      $grid.clearEdit()
    }
  }

  const removeRowEvent = async (row, index) => {
    const $grid = xGrid8.value[index]
    // console.log($grid.data.length,'====');

    // if($grid.data.length === 1){
    //   VXETable.modal.message({ content: '至少需要保留一条数据', status: 'error' })
    //   return
    // }

    const type = await VXETable.modal.confirm('您确定要删除该数据?')
    if ($grid) {
      if (type === 'confirm') {
        await $grid.remove(row)
      }
    }
  }
  const addInventor = (index) => {
    const $grid = xGrid8.value[index]
    $grid.insert({})
  }

  onMounted(() => {
    if (props.formData.length != 0) {
      formList.value = props.formData
    }
  })

  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  })

  const handlePageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    // findList()
  }

  const handTimeChange = (e, row) => {
    const data1 = new Date(e[0])
    const data2 = new Date(e[1])
    if (row.dayNum == null) {
      console.log(1)

      totalDay.value = getDaysBetweenDates(data1, data2)
      row.dayNum = totalDay.value
    }
  }

  function getDaysBetweenDates(date1, date2) {
    // 确保 date1 和 date2 是合法的日期对象
    if (!date1 || !date2) {
      throw new Error('Both arguments must be valid Date objects.')
    }
    // 获取两个日期之间的时间差（毫秒）
    const timeDifference = Math.abs(date2.getTime() - date1.getTime())

    // 将时间差转换为天数
    const daysDifference = Math.ceil(timeDifference / (1000 * 3600 * 24))

    return daysDifference
  }

  // 表格高度计算
  const height = ref(0)
  interface BaseTableHeight {
    (padding: number): number
  }
  const $baseTableHeight = inject<BaseTableHeight>('$baseTableHeight')
  onBeforeMount(() => {
    window.addEventListener('resize', handleHeight)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleHeight)
  })

  const handleHeight = () => {
    height.value = $baseTableHeight(0)
  }

  const computeTotal = (row, a, b) => {
    row.total = (parseFloat(a) + parseFloat(b)).toFixed(2)
    return row
  }

  function numberToChinese(num) {
    // 定义一个数组来存储数字对应的汉字
    const chineseNumbers = [
      '零',
      '一',
      '二',
      '三',
      '四',
      '五',
      '六',
      '七',
      '八',
      '九',
    ]
    // 返回对应的汉字
    return chineseNumbers[num]
  }
  defineExpose({
    submit,
  })
</script>

<style scoped lang="scss">
  .form-inline {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-row-gap: 16px;
    grid-column-gap: 20px;
    :deep(.el-form-item__label) {
      padding: 0 5px 0 0;
    }

    :deep(.el-form-item) {
      margin-right: 0px;
      margin-bottom: 0px;
    }
  }

  .mt20 {
    margin-top: 20px;
  }

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .card-list {
    margin-top: 20px;
  }
</style>
